// 插入区间

package Leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

class solution_057 {
    public int[][] insert(int[][] intervals, int[] newInterval) {
        int length = intervals.length;
        int start = newInterval[0];
        int end = newInterval[1];
        List<int[]> result = new ArrayList<>();
        for (int i = 0; i < length; i++) {
            if (newInterval[0] >= intervals[i][0] && newInterval[0] <= intervals[i][1]) {
                start = intervals[i][0];
            }
            if (newInterval[1] >= intervals[i][0] && newInterval[1] <= intervals[i][1]) {
                end = intervals[i][1];
            }
        }
        for (int i = 0; i < length; i++) {
            if (intervals[i][1] < start || intervals[i][0] > end)
                result.add(result.size(), new int[] { intervals[i][0], intervals[i][1] });
        }
        result.add(result.size(), new int[] { start, end });
        int[][] ans = result.toArray(new int[result.size()][]);
        Arrays.sort(ans, new Comparator<int[]>() {
            public int compare(int[] o1, int[] o2) {
                if (o1[0] == o2[0])
                    return o1[1] - o2[1];
                return o1[0] - o2[0];
            }
        });
        return ans;
    }
}

public class Solution057 {

}
